const { request } = require('../../utils/request');

Page({
  data: {
    email: '',
    code: '',
    password: '',
    codeBtnText: '发送验证码',
    codeBtnDisabled: false,
    codeTimer: null
  },
  onEmailInput(e) {
    this.setData({ email: e.detail || '' });
  },
  onCodeInput(e) {
    this.setData({ code: e.detail || '' });
  },
  onPasswordInput(e) {
    this.setData({ password: e.detail || '' });
  },
  onSendCode() {
    const { email, codeBtnDisabled } = this.data;
    if (codeBtnDisabled) return;
    if (!email) {
      wx.showToast({ title: '请输入邮箱', icon: 'none' });
      return;
    }
    this.setData({ codeBtnDisabled: true });
    request({
      url: '/member/sendCode',
      method: 'POST',
      data: { email },
    }).then(res => {
      if (res.code === '200') {
        wx.showToast({ title: '验证码已发送', icon: 'success' });
        this.startCodeTimer();
      } else {
        wx.showToast({ title: res.msg || '发送失败', icon: 'none' });
        this.setData({ codeBtnDisabled: false });
      }
    }).catch(() => {
      wx.showToast({ title: '网络错误', icon: 'none' });
      this.setData({ codeBtnDisabled: false });
    });
  },
  startCodeTimer() {
    let countdown = 60;
    this.setData({ codeBtnText: `${countdown}s`, codeBtnDisabled: true });
    const timer = setInterval(() => {
      countdown--;
      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({ codeBtnText: '发送验证码', codeBtnDisabled: false });
      } else {
        this.setData({ codeBtnText: `${countdown}s` });
      }
    }, 1000);
    this.setData({ codeTimer: timer });
  },
  onRegister() {
    const { email, code, password } = this.data;
    if (!email) {
      wx.showToast({ title: '请输入邮箱', icon: 'none' });
      return;
    }
    if (!code) {
      wx.showToast({ title: '请输入验证码', icon: 'none' });
      return;
    }
    if (!password) {
      wx.showToast({ title: '请输入密码', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '注册中...' });
    request({
      url: '/member/register',
      method: 'POST',
      data: { email, code, password },
    }).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        wx.showToast({ title: '注册成功', icon: 'success' });
        setTimeout(() => {
          wx.redirectTo({ url: '/pages/login/index' });
        }, 1500);
      } else {
        wx.showToast({ title: res.msg || '注册失败', icon: 'none' });
      }
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  },
  onUnload() {
    if (this.data.codeTimer) {
      clearInterval(this.data.codeTimer);
    }
  },
  onGoToLogin() {
    wx.navigateTo({ url: '/pages/login/index' });
  }
}); 